<?php
class AccountModel extends BaseModel 
{   
	function processLogin($provided_email, $provided_challenge) 
	{
		$BAD_LOGIN_DATA_MESSAGE = "Neteisingi prisijungimo duomenys";
		$LOGIN_SUCCESS_MESSAGE = "Prisijungta kaip $provided_email";
		
		$chlgen = new ChallengeGenerator(false);
		// get challenge variable
		$session_challenge_var = $chlgen->getChallengeVar('challenge');
		
		// get a "fresh" version of the page
		//header('Cache-control:must-revalidate');
		$db_user_data = DbCommunicator::fetchIdPasswordByEmail($this->pdo, $provided_email);
		$db_md5_password = $db_user_data['password'];
		
		// tokio emailo dbazėje nėra
		if ($db_md5_password == null) 
		{
			if (isset($_SESSION['current_user'])) {
				unset($_SESSION['current_user']);
			}
			$returnObject['messages'][] = $BAD_LOGIN_DATA_MESSAGE;
			$returnObject['success'] = false;
			return json_encode($returnObject);		
		}
		
		// nuo čia - emailas duomenų bazėje yra
		$server_challenge = md5($db_md5_password . $session_challenge_var);
		
		// sutampa challenge, reiškia buvo geras slaptažodis
		if ($server_challenge == $provided_challenge) 
		{
			$_SESSION['current_user'] = $db_user_data['id'];
			$returnObject['messages'][] = $LOGIN_SUCCESS_MESSAGE;
			$returnObject['success'] = true;
			return json_encode($returnObject);	
		}        
		else // nesutampa challenge, reiškia buvo blogas slaptažodis
		{
			if (isset($_SESSION['current_user'])) {
				unset($_SESSION['current_user']);
			}
			$returnObject['messages'][] = $BAD_LOGIN_DATA_MESSAGE;
			$returnObject['success'] = false;
			return json_encode($returnObject);		
		}
	}  
}